package com.ruben;

import com.alibaba.fastjson.JSON;
import com.ruben.pojo.dto.PageDTO;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.util.StreamUtils;

import javax.ws.rs.core.UriBuilder;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @ClassName: HttpDemo
 * @Description: 我还没有写描述
 * @Date: 2021/2/5 0005 19:48
 * *
 * @author: <achao1441470436@gmail.com>
 * @version: 1.0
 * @since: JDK 1.8
 */
public class HttpDemo {
    public static void main(String[] args) throws IOException {
        // 指定url和参数
        HttpPost request = new HttpPost(UriBuilder.fromUri("http://localhost:8080/user/userList").build());
        // 添加header，指定请求头中Content-Type为application/json
        request.setHeader("Content-Type", "application/json");
        // 放入参数到requestBody里
        request.setEntity(new StringEntity("{\"pageNum\":1,\"pageSize\":20,\"keyword\":\"supa\"}"));
        // 构建请求
        CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(RequestConfig.DEFAULT).build();
        // 执行请求，返回响应数据
        CloseableHttpResponse response = httpClient.execute(request);
        // 使用org.springframework.util.StreamUtils.copyToString去把响应回来的数据InputStream转换为String
        String responseData = StreamUtils.copyToString(response.getEntity().getContent(), Charset.defaultCharset());
        // 打印响应数据
        System.out.println(responseData);
    }


    private static void getRequest() throws IOException {
        // 指定url和参数,可以在queryParam后继续追加参数
        HttpGet request = new HttpGet(UriBuilder.fromUri("http://127.0.0.1:8080/user/say").queryParam("word", "xxx").build());
        // 构建请求,这里setDefaultRequestConfig指定请求配置，RequestConfig.DEFAULT为默认请求配置，这里我们自定义一个RequestConfig.custom().build()，指定请求超时时间为3000,最大重定向次数为1次
        CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(RequestConfig.custom().setConnectionRequestTimeout(3000).setMaxRedirects(1).build()).build();
        // 执行请求，返回响应数据
        CloseableHttpResponse response = httpClient.execute(request);
        // 使用org.springframework.util.StreamUtils.copyToString去把响应回来的数据InputStream转换为String
        String responseData = StreamUtils.copyToString(response.getEntity().getContent(), Charset.defaultCharset());
        // 打印响应数据
        System.out.println(responseData);
    }
}
